/**
  ******************************************************************************
  * @author     Chris
  * @since      2024/6/14 22:30
  *
  * @file       hd_key.c
  * @brief      KEY Hardware Driver.
  *
  * @note       This file contains the hardware driver for the KEY.
  *
  * @warning    None.
  ******************************************************************************
  * Change Logs:
  *   Date           Author       Notes
  *   2024/6/14      Chris        the first version
  *
  ******************************************************************************
  */

#include "air001xx_ll_gpio.h"
#include "delay.h"
#include "hd_key.h"


/**
 * @brief   按键初始化
 * @note    这里的按键接 PA0，触发后电平拉高。
 * @param   this struct KEY
 * @retval  无
 */
void Key_init(const Key *this) {
    this->gpio->init(this->gpio);
}

/**
 * @brief   获取按键返回值
 * @note    无
 * @param   无
 * @retval  0，按键弹起；1，按键按下。
 */
uint8_t Key_getKeyNum(const Key *this) {
    uint8_t keyNum = 0;

    if (this->gpio->getBit(this->gpio) != RESET) {
        delay_ms(15);
        while (this->gpio->getBit(this->gpio) != RESET);    // 等待按键松手
        delay_ms(15);
        keyNum = 1;
    }

    return keyNum;
}


static Key *build(GPIO *gpio) {
    Key *key = malloc(sizeof(Key));

    Driver_add(key, GEN_PERM);

    gpio->Mode  = LL_GPIO_MODE_INPUT;
    gpio->Speed = LL_GPIO_SPEED_FREQ_HIGH;

    key->gpio      = gpio;
    key->init      = &Key_init;
    key->getKeyNum = &Key_getKeyNum;

    return key;
}

const struct KeyClass KeyBuilder = {.build = &build};
